#!/usr/bin/env python
import os
import jinja2
#from google.appengine.ext import webapp
#from google.appengine.ext.webapp.util import run_wsgi_app
#from google.appengine.ext.webapp import template
import logging
import modules.Warehouse
from modules.Warehouse import box
from modules.Warehouse import stuff
from modules.Warehouse import Warehouse 
from modules.Predef import Predef as PRE
from modules.parser import parser


class Cell:
        
    ####################################################
    # Initialize
    ####################################################
    def __init__(self,request,response):
        self.request=request
        self.response=response
        self.message=''
        self.errmessage=''

        self.door=self.request.get('doorplate')
        self.Ware=Warehouse(self.door)
        label=self.request.get('label')

        # New settings
        self.b=box(label)
        if label != '':
            pack=self.Ware.CHECKOUT(label)
            if pack is not None:
                self.b.update(eval(pack))
        else:
            self.b=box(label)
            self.ERRMESSAGE("IMPOSSIBLE!!!Empty box!!!")


    ####################################################
    # For message
    ####################################################
    def MESSAGE(self,m):
        self.message=PRE.genMessage(self.message,m)

    def ERRMESSAGE(self,m):
        self.errmessage=PRE.genMessage(self.errmessage,"ERROR:"+m)

    ####################################################
    # Show the content
    ####################################################
    def getContent(self, t):
        
        st_new=stuff(self.request.get('pattern'),self.request.get('message'), \
                [self.request.get('lambda'), self.request.get('p1'), self.request.get('p2')])

        temp_path=os.path.join(
                os.path.dirname(__file__),
                "../templates/")

        temp=jinja2.Environment(loader=jinja2.FileSystemLoader(temp_path)).get_template(t)

        return temp.render(
                {
                    'doorplate':self.door,
                    'b':self.b,
                    'e':self.errmessage,
                    'm':self.message,
                    'n':st_new,
                    })


    ####################################################
    # Read and Check settings to GET
    ####################################################
    def doGet(self):
        self.response.out.write(self.getContent('editsetting.html'))

    ####################################################
    # Read and Check settings to POST
    ####################################################
    def doPost(self):

        if not self.b.setUrl(self.request.get('url')):
            self.ERRMESSAGE('Invalid URI!')

        elif not self.b.setTo(self.request.get('mailto'),self.request.get('topic')):
            self.ERRMESSAGE('Invalid Email address!')

        else:
            for k in self.b.stuffs.keys():
                # check deleted item
                if self.request.get('hidden_'+k) == 'Deleted':
                    self.b.delItem(k)
                    #logging.info("<{}> has been deleted!".format(k) )
                    self.MESSAGE('Success: <{}> has been deleted!'.format(k))
                # check update item
                elif not self.b.updateItem(k, self.request.get('pattern_'+k), self.request.get('message_'+k), 
                        [self.request.get('lambda_'+k), self.request.get('p1_'+k), self.request.get('p2_'+k)]):
                    self.ERRMESSAGE('Invalid data in <{}>'.format(k))

            # check the new item
            if (self.request.get('item')!='') and (not self.b.addItem(self.request.get('item'), self.request.get('pattern'), 
                    self.request.get('message'), [self.request.get('lambda'), self.request.get('p1'), self.request.get('p2')])):
                self.ERRMESSAGE('Invalid new item!')

            # check the whole box again
            elif not self.b.isValid():
                self.ERRMESSAGE('Invalid box!')

            else:
                self.MESSAGE('Success: The new data has been updated!')
                p=parser(self.b).run()
                if p is not None:
                    self.MESSAGE('Report:{}'.format(p.report(isHTML=True)))
                    #self.Ware.CHECKIN(self.b.getLabel(),self.b.export())
                    l,b=p.export()
                    #logging.info("'{}':{}".format(l,b))
                    self.Ware.CHECKIN(l,b)

        self.response.out.write(self.getContent('editsetting.html'))
